package org.dru.clay.respository.artifact;

import java.util.regex.Pattern;

public class VersionPattern implements Comparable<VersionPattern> {
	private final Pattern allowedCharactersRegex = Pattern.compile("[0-9_\\-a-z\\.\\+]+", Pattern.CASE_INSENSITIVE);

	private final String original;
	private final Pattern regexp;
	private final boolean dynamic;

	public VersionPattern(String version) {
		if (!allowedCharactersRegex.matcher(version).matches()) {
			throw new IllegalArgumentException("Invalid dynamic version '" + version + "'");
		}
		final String pattern = version.replaceAll("\\+", ".+");

		this.original = version;
		this.regexp = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
		this.dynamic = version.indexOf('+') >= 0;
	}

	public boolean isDynamic() {
		return dynamic;
	}

	public String getOriginal() {
		return original;
	}

	public boolean matches(String version) {
		return regexp.matcher(version).matches();
	}

	public boolean matches(Version version) {
		return regexp.matcher(version.plain()).matches();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((original == null) ? 0 : original.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		VersionPattern other = (VersionPattern) obj;
		if (original == null) {
			if (other.original != null)
				return false;
		} else if (!original.equals(other.original))
			return false;
		return true;
	}

	@Override
	public int compareTo(VersionPattern o) {
		return original.compareTo(o.original);
	}

	public String toString() {
		return original;
	}
}
